<template>
  <div>
    <a-table size="small" :dataSource="dataSource" :columns="columns" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'time'">
          <span>
            <a-tag
              :color="record.time <= 300 ? 'success' : record.time <= 1000 ? 'warning' : 'error'"
            >
              {{ record.time }}ms
            </a-tag>
          </span>
        </template>
      </template>
    </a-table>
    <!--分页组件-->
    <a-pagination
      style="margin-top: 10px"
      size="small"
      v-model:current="page"
      :total="total"
      show-size-changer
      show-quick-jumper
      :show-total="(total) => `共有 ${total} 条数据`"
      @showSizeChange="onShowSizeChange"
      @change="pageChange"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, watch } from 'vue';
  import { getUserLogsApi } from '/@/api/user';

  const columns = [
    {
      title: '行为',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: 'IP',
      dataIndex: 'requestIp',
      key: 'requestIp',
    },
    {
      title: 'IP来源',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
      key: 'browser',
    },
    {
      title: '请求耗时',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];

  export default defineComponent({
    setup() {
      const dataSource = ref<any>([]);
      const total = ref<number>(0);
      const page = ref<number>(1);
      const pageSize = ref<number>(10);

      const pageChange = (current: number) => {
        page.value = current;
      };

      const onShowSizeChange = (_current: number, size: number) => {
        page.value = 1;
        pageSize.value = size;
      };

      const loadLogs = async () => {
        let res = await getUserLogsApi({
          page: page.value - 1,
          size: pageSize.value,
          sort: 'id,desc',
        });
        dataSource.value = res?.content;
        total.value = res?.totalElements;
      };

      watch([page, pageSize], () => {
        loadLogs();
      });

      return { page, total, dataSource, pageChange, onShowSizeChange, columns, loadLogs };
    },
  });
</script>
